#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
void *read(void *arg);
void *accu(void *arg);
static sem_t sem_one;
static sem_t sem_two;
static int num;
//线程A从用户输入得到值后存入全局变量num，此时线程B将取走该值并累加。该过程共进行5次，完成后输出总和并退出程序
int main(int argc,char *argv[])
{
	pthread_t id_t1,id_t2;
	//创建信号量
	//int sem_init(sem_t *sem,int pshared,unsigned int value)
	sem_init(&sem_one,0,0);
	sem_init(&sem_two,0,1);
	
	pthread_create(&id_t1,NULL,read,NULL);
	pthread_create(&id_t2,NULL,accu,NULL);

	pthread_join(id_t1,NULL);
	pthread_join(id_t2,NULL);
	//信号量销毁
	//int sem_destroy(sem_t *sem)
	sem_destroy(&sem_one);
	sem_destroy(&sem_two);
	return 0;
}	
void *read(void *arg)
{
	int i;
	for(i=0;i<5;i++)
	{
		fputs("Input num:",stdout);
		//int sem_wait(sem_t *sem)
		sem_wait(&sem_two);//信号量减一
		scanf("%d",&num);
		//int sem_post(sem_t *sem)
		sem_post(&sem_one);//信号量加一
	}
	return NULL;
}
void *accu(void *arg)
{
	int sum=0,i;
	for(i=0;i<5;i++)
	{
		sem_wait(&sem_one);
		sum+=num;
		sem_post(&sem_two);
	}
	printf("Result:%d\n",sum);
	return NULL;
}
